package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author caiwl
 * @date 2020/4/27 9:39
 */
@SpringBootApplication
@RestController
public class LoginApplication {
    public static void main(String[] args) {
        SpringApplication.run(LoginApplication.class, args);
    }

    private final String SESSION_ATTR_SSO_KEY = "user";
    private final String SUPER_ADMIN_USER = "yufumin";
    private final String SUPER_ADMIN_PWD = "123456";

    @RequestMapping("/login")
    public String home(HttpServletRequest request, String user, String password) {
        HttpSession session = request.getSession();
        String attrUser = (String) session.getAttribute(SESSION_ATTR_SSO_KEY);
        // 检查是否已登录
        if (Objects.nonNull(attrUser)) {
            return "is logged in";
        }
        // 未登录，检查用户名密码是否匹配，此处只是示例，生产环境应去数据库校验
        if (Objects.equals(SUPER_ADMIN_USER, user) && Objects.equals(SUPER_ADMIN_PWD, password)) {
            // 校验成功，设置SSO_KEY
            session.setAttribute(SESSION_ATTR_SSO_KEY, user);
            return "login success";
        } else {
            return "user or password error";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 退出时，直接删除SSO_KEY，不操作session本身
        request.getSession().removeAttribute(SESSION_ATTR_SSO_KEY);
        return "logout SSO";
    }
}
